/*
 * @Date: 2024-01-03 10:12:29
 * @LastEditors: lyx
 * @LastEditTime: 2024-01-30 14:51:41
 * @FilePath: \mt-middleware-server\src\gateway\ws.gateway.ts
 * @Description:
 */
import {
  ConnectedSocket,
  MessageBody,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  WsResponse,
} from '@nestjs/websockets';
import { Socket, Server } from 'socket.io';
import { Inject, Logger } from '@nestjs/common';
import * as ws from 'ws';
import { messageWS as MessageWS } from './websocket';
import { FeishuService } from 'src/feishu/feishu.service';
import { ObpService } from 'src/obp/obp.service';
import { get } from 'lodash';
import { ConfigService } from '@nestjs/config';
import { LJY_TaskCardUrl } from './msg/ljy/feishu';

// 注意ws端口号不能和http端口号一样，否则会冲突
@WebSocketGateway(3002, {
  cors: {
    origin: '*',
  },
})
export class WsStartGateway {
  constructor(
    private readonly obpService: ObpService,
    private readonly feishuService: FeishuService,
    private readonly configService: ConfigService,
  ) {} //
  @WebSocketServer() server: Server;
  private socket;
  private reConnectCount = 0;

  afterInit(server: Server) {
    console.log('去连接 消息中心 ws ===>123!');
    // // 创建一个 WebSocket 客户端，连接到 Java 端的地址
    // const client = require('socket.io-client')('http://localhost:8080');
    // // 监听 Java 端发送的消息
    // client.on('message', (data) => {
    //   this.logger.log('Received message from Java: ' + data);
    //   // 将消息转发给 NestJS 端的客户端
    //   this.server.emit('message', data);
    // });

    // this.initWS();
  }

  // SubscribeMessage里面的字符串代表类型，就是send event的值
  @SubscribeMessage('events')
  handleEvent(
    @MessageBody() data: string,
    @ConnectedSocket() client: Socket,
  ): WsResponse<unknown> {
    console.log('ws hello data', data);
    const event = 'events';
    return {
      event,
      data: {
        msg: 'ws 收到信息后返回',
      },
    };
  }

  initWS() {
    console.log('initWS==>');
    // const url = 'wss://web-monitor-storage.supcon5t.com/api/v1/ws';
    // const url = 'ws://192.168.182.44:8110/supRto?itemId=120';
    // const url = 'ws://k8sm1.supcon5t.com:31553/websocket/supWs?userId=1';
    // const url = 'ws://k8sm1.supcon5t.com:31553/boiler-web/websocket/supWs?moduleId=BOILER&serverName=BOILER';
    const url =
      'wss://obp-dev.supcon5t.com/xpt-app-manager-web/api/websocket/supWs?moduleId=evaluation-task&serverName=evaluation-task&level=1';
    // const url =
    //   'ws://k8sm1.supcon5t.com:31553//catalyzer-web/ws/supWs?userId=1&appId=catalyzer';

    this.socket = new MessageWS({
      url,
      // eslint-disable-next-line complexity
      onmessage: async (message: any) => {
        console.log('websData message==>', message);

        const a = message.message;
        // eslint-disable-next-line no-eval
        const websData = JSON.parse(a);
        const { type = '', data } = websData;
        console.log('websData==>', websData);
        if (type === 'pong') {
          // reConnectCount.current = 3;
          // sessionRef.current = websData.data.socketSessionId?.toString();
          // if (data?.sessionId) {
          //   setSessionId(data?.sessionId);
          //   await remindOpenWS(data?.sessionId);
          // }
        } else if (type === 'messager') {
          const { messageType = '' } = data;
          if (messageType === 'mt') {
            // ! 命中 移动端消息
            this.adapterOfWs(data);
          }
        }
      },
      onclose: (e: any) => {
        this.reConnectCount = this.reConnectCount - 1;
        if (this.reConnectCount) {
          //  这边是重新连接ws
          setTimeout(() => {
            this.initWS();
          }, 15000);
        } else {
          console.log('连接断开~');
        }
      },
    });
  }

  adapterOfWs(data: IWSMsg_MT_Data) {
    //   {
    //     "evaluationPoint": 0,
    //     "plantForm": "feishu",
    //     "userId": 1000,
    //     "url": "liyixingzuishuai.com",
    //     "messageType": "mt",
    //     "appType": "h5",
    //     "taskHisId": 1750685995245969400,
    //     "evaluationStatus": 10
    // }
    console.log('adapterOfWs==>', data);
    const { plantForm = '' } = data || {};
    if (plantForm === 'feishu') {
      this.feishu(data as IWSMsg_LJY_Data);
    }
  }

  getMsgDto(data: IWSMsg_LJY_Data, openId = '') {
    const { appType, taskHisId, id, url = '' } = data;
    let dto: any = {
      tenant: appType,
      // ! 飞书 推送应用 id
      appId: this.configService.get(`feishu.app.tenant.${appType}`),
      // receivePhone: '13616859570',
      receive_id: openId,
      content: 'test content111',
    };
    if (!url) {
      // 文字消息
      dto = {
        ...dto,
        msg_type: 'text',
      };
    } else {
      const cUrl = LJY_TaskCardUrl({
        url,
        id,
        taskHisId,
      });
      // 卡片消息
      dto = {
        ...dto,
        url: cUrl,
        msg_type: 'interactive',
        program_type: 'h5', // ! 目前写死
      };
    }
    return dto;
  }

  async feishu(data: IWSMsg_LJY_Data) {
    console.log('feishu==>', data);
    const { userId, plantForm, appType, url = '' } = data;
    // 1. 根据 userId 获取 小平台对应用户的 信息
    const userInfo = await this.obpService.queryOpenIdByUserId({ userId });
    // 2. 根据平台和应用获取 openId
    if (!userInfo?.id) {
      return;
    }
    const { additional = {} } = userInfo;
    const openId = get(additional, `${plantForm}.${appType}`, '');
    if (!openId) {
      console.log('没有获取到该用户的指定 openId');
    }
    const dto = this.getMsgDto(data, openId);
    // 3. 推送消息
    this.feishuService.sendMessagesToUser({
      ...dto,
    });
  }
}
